package org.xhy.hrm.globle;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.xhy.hrm.util.AjaxResult;

import java.util.List;

/**
 * 全局异常处理
 */
//RestController的增强版，该注解下类的方法在其他controller执行前后做一些事
@RestControllerAdvice
public class GlobleExceptionHandler {

    @ExceptionHandler(value = GlobleException.class)
    public AjaxResult globleExceptionHandler(GlobleException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后再试...");
    }

    // 捕获的MethodArgumentNotValidException异常，通过断点看到e中的error数据，循环追加
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult beanMethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder builder = new StringBuilder();
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        errors.forEach(objectError -> {
            String message = objectError.getDefaultMessage();
            builder.append(message).append(";");
        });
        return AjaxResult.me().setSuccess(false).setMessage(builder.toString());
    }
}
